import { domain } from "./config.js"
import axios from 'axios'
import store from '@/store'
import { MessageBox, Message } from 'element-ui'
import { getToken } from "./auth.js"

function httpAxios(url,method,data){
	return new Promise((resolve, reject) => {
		axios({
			url: domain + url,
			method: method,
			headers:{
				'token': getToken(),
				'Content-Type': 'application/json',
			},
			params: method=='get'||method=='GET'?data:null,
			data:method=='get'||method=='GET'?null:data,
		}).then(function(res){
		    if (res.data.code == "1010" || res.data.code == "1020" || res.data.code == "1030") {
		    	reject(res.data);
				console.log(res.data);
			    MessageBox.confirm('登录过期是否重新登录', res.data.msg, {
			      confirmButtonText: '重新登陆',
			      cancelButtonText: '取消',
			      type: 'warning'
			    }).then(() => {
			      store.dispatch('user/resetToken').then(() => {
			        location.reload()
			      })
			    })
		    }else if (res.data.code ==1) {
		        resolve(res.data);
		    }else{
		    	Message({
					message: res.data.msg,
					type: 'error',
					duration: 2000
				});
				reject(res.data);
				console.log(res.data);
		    }
		}).catch(function(err){
			Message({
				message: "系统繁忙请稍后再试！！！",
				type: 'error',
				duration: 2000
			});
		    reject(err);
		});
	})
};
function downLoadFile(url,method,data){
	return new Promise((resolve, reject) => {
		axios({
			url: domain + url,
			method: method,
			responseType: 'blob',
			headers:{
				'token': getToken()
			},
			params: method=='get'||method=='GET'?data:null,
			data:method=='get'||method=='GET'?null:data,
		}).then(function(res){
			if(res.status==200){
				resolve(res.data);
			}else{
				Message({
					message: "导出失败请联系管理员",
					type: 'error',
					duration: 2000
				});
				reject(res.data);
			};
		}).catch(function(err){
			Message({
				message: "系统繁忙请稍后再试！！！",
				type: 'error',
				duration: 2000
			});
		    reject(err);
		});
	})
}

export { 
	httpAxios,
	downLoadFile
}